//
//  DCAuthContactsController.m
//  Demo
//
//  Created by zhaolin on 2023/1/9.
//

#import "DCAuthContactsController.h"
#import "DCAuthInfoCommonCell.h"
#import "DCAuthInfoUIModel.h"
#import "DCAuthFooterView.h"
#import "DCAuthContactsInfoCell.h"
#import "DCPersonalInfoPicker.h"
#import "DCSystemContactsController.h"
//#import <Contacts/Contacts.h>

@interface DCAuthContactsController ()<UITableViewDelegate,UITableViewDataSource,DCAuthInfoCommonCellDelegate,AuthContactsInfoCellDelegate,DCAuthFooterViewDelegate,SystemContactsDelegate>

@property (nonatomic, strong) DCPersonalInfoPicker *pickerView;

@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) NSIndexPath *currentIndex;

@property (nonatomic, strong) NSArray *typeArr;

//@property (nonatomic, strong) CNContactPickerViewController * peoplePickVC;
@end

@implementation DCAuthContactsController

//- (CNContactPickerViewController *)peoplePickVC {
//    if(!_peoplePickVC) {
//        _peoplePickVC = [[CNContactPickerViewController alloc] init];
//        _peoplePickVC.delegate = self;
//        _peoplePickVC.displayedPropertyKeys = @[CNContactPhoneNumbersKey]; // 只显示手机号
//
//    }
//    return _peoplePickVC;
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitleName:@"Contacts"];
    // Do any additional setup after loading the view.
    
}

- (void)configureAlloc {
    [super configureAlloc];
    self.step = @"CONTACT_INFO";
    self.dataSource = @[].mutableCopy;
    _typeArr = @[@"RELATIONSHIP1",@"RELATIONSHIP2"];

    NSArray *titleArr = @[@"First contact person",@"Second contact person"];
    NSArray *placeholderArr = @[@"Select",@"Select"];
    NSArray *cellTypeArr = @[@(DCAuthInfoCommonCellTypeRightRight),@(DCAuthInfoCommonCellTypeRightRight)];
    NSArray *canEdit = @[@(NO),@(NO)];
    for (int i = 0; i<titleArr.count; i++) {
        DCAuthInfoUIModel *model = [DCAuthInfoUIModel new];
        model.title = [titleArr objectAtIndex:i];
        model.placeholder = [placeholderArr objectAtIndex:i];
        model.celltype = [[cellTypeArr objectAtIndex:i] intValue];
        model.canEdit = [[canEdit objectAtIndex:i] boolValue];
        [self.dataSource addObject:model];
    }
}

- (void)configureUI {
    [super configureUI];
    [self _setCurrntStep:3];
    [self configureTable];
    [self.tableView registerClass:[DCAuthInfoCommonCell class] forCellReuseIdentifier:NSStringFromClass(DCAuthInfoCommonCell.class)];
    [self.tableView registerClass:[DCAuthContactsInfoCell class] forCellReuseIdentifier:NSStringFromClass(DCAuthContactsInfoCell.class)];
    [self.tableView registerClass:[DCAuthFooterView class] forHeaderFooterViewReuseIdentifier:NSStringFromClass(DCAuthFooterView.class)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.topRadiusView.mas_bottom).mas_equalTo(-30);
    }];
    [self.view bringSubviewToFront:self.tableView];
 
    mWeakSelf;
    _pickerView = [[DCPersonalInfoPicker alloc] initWithFrame:CGRectZero];
    _pickerView.cancelCallBack = ^(DCAuthPersonalInfoModel * _Nullable model) {
        [weakSelf pickViewShow:NO];
    };
    _pickerView.sureCallBack = ^(DCAuthPersonalInfoModel * _Nullable model) {
        [weakSelf pickViewShow:NO];
        DCAuthInfoUIModel *uiModel = [weakSelf.dataSource objectAtIndex:weakSelf.currentIndex.row];
        uiModel.personalInfoModel = model;
        uiModel.content = model.remark;
        DCSystemContactsController *systemConVC = [[DCSystemContactsController alloc] init];
        systemConVC.delegate = weakSelf;
        [weakSelf.navigationController pushViewController:systemConVC animated:YES];
    };
    [self.view addSubview:_pickerView];
    [_pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view.height);
        make.bottom.mas_equalTo(-self.view.height);
    }];
    
//    NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
//    CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
}

- (void)getDictListWithType:(NSString *)type {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [DCHttpRequest DCDictListWithType:type complate:^(NSURLSessionDataTask * _Nonnull operation, DCResponseData * _Nonnull responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (responseObject.code == 200) {
            NSArray *arr = [DCAuthPersonalInfoModel mj_objectArrayWithKeyValuesArray:[responseObject.data objectForKey:@"dictList"]];
            [self.pickerView updateDataArr:arr];
            [self pickViewShow:YES];
            DLog(@"%@",arr);
        } else {
            [DCDCToast toastText:responseObject.message];
        }
    }];
}

#pragma mark - tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DCAuthInfoUIModel *model = [self.dataSource objectAtIndex:indexPath.row];
    if(model.content && model.content.length){
        DCAuthContactsInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(DCAuthContactsInfoCell.class)];
        cell.delegate = self;
        cell.indexPath = indexPath;
        NSArray *contactdata0 = [model.content componentsSeparatedByString:@"  "];
        NSString *name0 = [contactdata0 firstObject];
        NSString *phoneNum0 = contactdata0.lastObject;
        [cell setDataWithContactName:name0 contactPhone:phoneNum0 realtion:model.personalInfoModel.remark];
        return cell;
    } else {
        DCAuthInfoCommonCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(DCAuthInfoCommonCell.class)];
        cell.delegate = self;
        cell.indexPath = indexPath;
        [cell configureDataWithModel:model];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    DCAuthInfoUIModel *model = [self.dataSource objectAtIndex:indexPath.row];
    if(model.content  && model.content.length) {
        return 215;
    } else {
        return 105;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    DCAuthFooterView *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass(DCAuthFooterView.class)];
    BOOL contentNull = [self allInfoContentNull];
    [footer setCommitBtnEnabled:!contentNull];
    footer.delegate = self;
    return footer;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 125;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}
#pragma mark -- DCAuthInfoCommonCellDelegate
- (void)authInfoCommonCellBegainEditingWithText:(NSIndexPath *)index {
    _currentIndex = index;
    NSString *type = [_typeArr objectAtIndex:index.row];
    [self getDictListWithType:type];
}

#pragma mark -- AuthContactsInfoCellDelegate
- (void)authContactsInfoCellReselect:(NSIndexPath *)indexPath {
    _currentIndex = indexPath;
    NSString *type = [_typeArr objectAtIndex:indexPath.row];
    [self getDictListWithType:type];
}

#pragma mark -- SystemContactsDelegate
- (void)systemContactsSelect:(NSString *)contact {
    DCAuthInfoUIModel *model = [self.dataSource objectAtIndex:_currentIndex.row];
    model.content = contact;
    [self.tableView reloadData];
}
#pragma mark --- DCAuthFooterViewDelegate
- (void)authFooterViewNextAction:(id _Nullable )sender {
    /* // data 格式为JSON字符串
     data: "{
     \"contact1\":\"523333\", // 第一联系人手机号
     \"contact1Name\":\"aaa\", // 第一联系人姓名
     \"relationship1\":\"1\", // 与第一联系人的关系
     \"contact2\":\"aaa\", // 第二联系人手机号
     \"contact2Name\":\"523344\",// 第二联系人姓名
     \"relationship2\":\"1\", // 与第二联系人的关系
     }"*/
    
    BOOL contentNull = [self allInfoContentNull];
    if(contentNull) {
        return;
    }
    
    NSMutableDictionary *mDic = @{}.mutableCopy;
    DCAuthInfoUIModel *model0 = [self.dataSource objectAtIndex:0];
    NSArray *contactdata0 = [model0.content componentsSeparatedByString:@"  "];
    NSString *name0 = [contactdata0 firstObject];
    NSString *phoneNum0 = contactdata0.lastObject;
    [mDic setValue:phoneNum0 forKey:@"contact1"];
    [mDic setValue:name0 forKey:@"contact1Name"];
    [mDic setValue:model0.personalInfoModel.typeName forKey:@"relationship1"];

    DCAuthInfoUIModel *model1 = [self.dataSource objectAtIndex:1];
    NSArray *contactdata1 = [model1.content componentsSeparatedByString:@"  "];
    NSString *name1 = [contactdata1 firstObject];
    NSString *phoneNum1 = contactdata1.lastObject;
    [mDic setValue:phoneNum1 forKey:@"contact2"];
    [mDic setValue:name1 forKey:@"contact2Name"];
    [mDic setValue:model1.personalInfoModel.typeName forKey:@"relationship2"];
    
    NSString *jsonStr = mDic.mj_JSONString;
    [self saveInfo2:jsonStr];

}

- (void)authFooterViewAgreementAction:(id _Nullable)sender {
    [self pushPrivacyAgreement];
}

- (BOOL)allInfoContentNull {
    BOOL contentNull= NO;
    for (int i = 0; i < self.dataSource.count-1; i++) {
        DCAuthInfoUIModel *model = self.dataSource[i];
        if(!model.content || !model.content.length) {
            contentNull = YES;
            break;
        }
    }
    return contentNull;
}
- (void)pickViewShow:(BOOL)show {
    [self.pickerView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(show?0:self.view.height);
        make.bottom.mas_equalTo(show?0:-self.view.height);
    }];
    self.pickerView.backgroundColor = [[UIColor colorWithString:@"#000000"] colorWithAlphaComponent:0];
    
    [UIView animateWithDuration:0.5 animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        self.pickerView.backgroundColor = [[UIColor colorWithString:@"#000000"] colorWithAlphaComponent:0.7];
    }];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */



@end
